package com.lu.sb210413.cameraDetection;


import com.sun.jna.Platform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class RTMPClient extends Thread {

    private String address;

    public RTMPClient (String address) {
        this.address = address;
    }

    @Override
    public void run() {
        try {
            String executeCommand = executeCommand();
            System.out.println("返回信息：\n" + executeCommand);
            if (StringUtils.isBlank(executeCommand)) {
                // TODO 数据库该相机不可用
            } else {
                // TODO 数据库该相机可用
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String executeCommand() throws IOException {
        java.lang.Process process = null;
        try {
            if (Platform.isWindows()) {
                process = Runtime.getRuntime().exec("ffprobe -v quiet -show_streams " + address);
            } else if (Platform.isLinux()) {
                String[] shell = {"/bin/bash", "-c", "ffprobe -v quiet -show_streams " + address};
                process = Runtime.getRuntime().exec(shell);
            }
        } catch (IOException e) {
            log.warn("ffmpeg未安装或指令不可用");
        }

        if (process == null) {
            return null;
        }

        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        StringBuilder stringBuilder = new StringBuilder();

        String line;

        while (StringUtils.isNotEmpty(line = reader.readLine())) {

            stringBuilder.append(line).append("\n");
        }

        return stringBuilder.toString();
    }

}
